package com.mooc.controller;

import com.mooc.biz.*;
import com.mooc.entity.*;
import com.mooc.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class MusicController {

    @Autowired
    MusicBiz musicBiz;
    @Autowired
    MessageBiz messageBiz;
    @Autowired
    LogBiz logBiz;
    @Autowired
    UserBiz userBiz;
    @Autowired
    ReviewBiz reviewBiz;

    /**
     * 普通日志写入
     *
     * @param loginUser
     * @param ip
     * @param type
     */
    public void setlog(User loginUser, String ip, String type) {
        Log log = new Log();
        log.setUserid(loginUser.getId());
        log.setUsername(loginUser.getUsername());
        log.setIp(ip);
        log.setType(type);
        logBiz.insert(log);
    }

    @RequestMapping(value = "music")
    // 主页课程查询
    public String music(HttpSession session, Map map) {
        List<Music> music = musicBiz.selectAllMusic();
        map.put("musics", music);
        return "musicindex";

    }

    @RequestMapping(value = "musicdetail")
    // 单课程主页
    public ModelAndView Musicindex(Long id, HttpSession session, ModelAndView mav) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            mav.setViewName("login");
            return mav;
        }
        Message message = new Message();
        message.setCourseid(id);
        message.setUserid(loginUser.getId());
        Message me = messageBiz.select(message);
        if (me == null) {
            mav.addObject("isSelect", false);
        } else {
            mav.addObject("isSelect", true);
        }
        Music music= musicBiz.selectByPrimaryKey(id);
        mav.addObject("music", music);
        mav.setViewName("musicdetail");
        return mav;

    }

    @RequestMapping(value = "insertMusic")
    // 加入课程
    public void insertMusic(Long musicid, String userid, HttpSession session, HttpServletRequest req,
                             HttpServletResponse response) throws IOException {
        String result = "订阅成功！";
        User user = (User) session.getAttribute("loginUser");
        Music c = musicBiz.selectByPrimaryKey(musicid);
        if (user.getVip() == null && "1".equals(c.getType())) {
            result = "此课程是会员课程，请购买会员！";
        } else {
            Message message = new Message();
            message.setCourseid(musicid);
            message.setUserid(userid);
            int i = messageBiz.insert(message);
            System.out.println(i);
            setlog(user, req.getRemoteAddr(), "订阅课程:" + c.getName());
        }
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print(result);
    }

    @RequestMapping(value = "deleteMusic")
    // 删除课程
    public String deleteMusic(Long musicid, String userid, HttpServletResponse response, HttpServletRequest req)
            throws IOException {
        Message message = new Message();
        message.setCourseid(musicid);
        message.setUserid(userid);
//        PrintWriter out = response.getWriter();
        int i = messageBiz.delete(message);
        User loginUser = userBiz.selectByPrimaryKey(userid);
        Music c = musicBiz.selectByPrimaryKey(musicid);
        setlog(loginUser, req.getRemoteAddr(), "取消课程：" + c.getName());
        String result = i > 0 ? "true" : "false";
        return result;
    }


    @RequestMapping(value = "musicshow")
    // 单课程视频
    public String musicvideo(Long musicid, HttpSession session, Map map) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }
        Music music = musicBiz.selectByPrimaryKey(musicid);
        if ("1".equals(music.getType())) {
            if (loginUser.getVip() == null) {
                return "vip";
            }
        }
        map.put("music", music);
        List<Review> reviews = reviewBiz.select(musicid);
        map.put("reviews", reviews);
        return "musicshow";
    }

    @RequestMapping(value = "subreviewMusic")
    // 提交评论
    public String subreview(HttpSession session, Review review,HttpServletRequest req) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }
        int vip ;
        if(loginUser.getVip()!=null){
            vip=1;
        }else{
            vip=0;
        }
        Music music = new Music();
        music.setId(Long.valueOf(review.getCourseid()));
        music.setLabel(reviewBiz.avglable(review.getCourseid()));
        musicBiz.updateByPrimaryKeySelective(music);
        review.setVip(vip);
        review.setSex(loginUser.getSex());
        review.setReviewid(DateUtil.getId());
        review.setUsername(loginUser.getUsername());
        reviewBiz.insert(review);
        setlog(loginUser, req.getRemoteAddr(), "发表评论，在'"+musicBiz.selectByPrimaryKey(review.getCourseid()).getName() +"'");
        return "redirect:musicshow?musicid=" + review.getCourseid();

    }


    @RequestMapping(value = "musicde")//课程详情界面
    public String musicde(String musicid, HttpSession session) {
        session.removeAttribute("msg");
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }else if(!"admin".equals(loginUser.getMission())&&!"showadmin".equals(loginUser.getMission())){
            //添加管理员的再次验证
            return "redirect:music";
        }
        if(musicid!=null) {
            Music music = musicBiz.selectByPrimaryKey(Long.parseLong(musicid));
            session.setAttribute("music", music);
            return "admin/music";
        }
        session.removeAttribute("music");
        return "admin/music";

    }
    @RequestMapping(value = "allmusic")//全部课程界面
    public String allmusicindex(int page, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }else if(!"admin".equals(loginUser.getMission())&&!"showadmin".equals(loginUser.getMission())){
            //添加管理员的再次验证
            return "redirect:music";
        }
        List<Music> musicss = musicBiz.selectAllMusic();
        int totalpage = 5;//一页的数量
        List<Music> musics = new ArrayList<Music>();
        int i1 = (musicss.size() - 1) / totalpage;
        session.setAttribute("maxpage", i1);
        for(int i = page*totalpage;i<page*totalpage+totalpage;i++){
            if(musicss.size()==i){
                session.setAttribute("musics", musics);
                session.setAttribute("page", page);
                return "admin/allmusic";
            }
            musics.add(musicss.get(i));
        }
        session.setAttribute("page", page);
        session.setAttribute("musics", musics);
        return "admin/allmusic";
    }

    @RequestMapping(value = "banmusic")//上下架课程
    public String banmusic(int type,Long musicid, HttpSession session,HttpServletRequest req) {
        User loginUser = (User) session.getAttribute("loginUser");
        int page = (int) session.getAttribute("page");
        if (loginUser == null) {
            return "login";
        }else if(!"admin".equals(loginUser.getMission())&&!"showadmin".equals(loginUser.getMission())){
            //添加管理员的再次验证
            return "redirect:music";
        }
        Music music = musicBiz.selectByPrimaryKey(musicid);
        Log log = new Log();
        log.setExecutor(loginUser.getUsername());
        log.setIp(req.getRemoteAddr());
        if(type==1) {//下架课程
            music.setPrice("1");
            log.setType("下架课程："+music.getName());
        }
        if(type==0) {//上架课程
            music.setPrice("0");
            log.setType("上架课程："+music.getName());
        }
        logBiz.insert(log);
        musicBiz.updateByPrimaryKeySelective(music);
        return "redirect:allmusic?page="+page;
    }

    @RequestMapping(value = "musicsave")//课程上传/修改
    public String musicsave(HttpServletRequest req, HttpSession session) {
        session.removeAttribute("msg");
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "login";
        }else if(!"admin".equals(loginUser.getMission())){
            //添加管理员的再次验证
            return "redirect:course";
        }
        musicBiz.savemusic(req);
        session.setAttribute("msg", "操作成功");
        return "admin/course";
    }

    @RequestMapping(value = "deletemusic")//删除课程
    public void deletemusic(Long musicid, String removepassword, HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User loginUser = (User) session.getAttribute("loginUser");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = resp.getWriter();
        if (!removepassword.equals("591284209")) {
            pw.print("0");
        } else {
            Music music = musicBiz.selectByPrimaryKey(musicid);
            musicBiz.deleteByPrimaryKey(String.valueOf(musicid));
            Log log = new Log();
            log.setExecutor(loginUser.getUsername());
            log.setIp(req.getRemoteAddr());
            log.setType("删除播客：" + music.getName());
            logBiz.insert(log);
            pw.print("课程：" + music.getName() + ",删除成功！请刷新页面后操作");
        }
    }
}
